import { OnInit, Component, Output, EventEmitter, ViewChild, Input } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { Validators, NgForm, FormGroup, FormControl, ValidationErrors, FormBuilder } from '@angular/forms';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { Observer, Observable } from 'rxjs';
import { FormUtil } from '@shared/utils/form-util';
import { CourseTeacherService } from 'src/app/project/service/icm/icm-start-course/start-course/course-teacher.service';
import { CourseTeacherDTO } from 'src/app/project/model/icm/icm-start-course/start-course/course-teacher.dto';
import { TeacherDTO } from 'src/app/project/model/icm/icm-system-user/teacher/teacher.dto';
import { CourseTypeDTO } from 'src/app/project/model/icm/icm-base/course-type/course-type.dto';
import { CourseDTO } from 'src/app/project/model/icm/icm-base/course/course.dto';
import { CourseService } from 'src/app/project/service/icm/icm-base/course/course.service';
import { TeacherSerivce } from 'src/app/project/service/icm/icm-system-user/teacher/teacher.service';
import { STColumn } from '@delon/abc';
import { format } from 'date-fns';

@Component({
  selector: 'app-start-course-detail',
  templateUrl: './start-course-detail.component.html',
  styles: [],
})
export class StartCourseDetailComponent implements OnInit {
  constructor(
    private msg: NzMessageService,
    private courseTeacherService: CourseTeacherService,
    private fb: FormBuilder,
    private courseService: CourseService,
    private teacherService: TeacherSerivce,
  ) {
    this.validateForm = this.fb.group({
      year: ['', [Validators.required]],
      termType: ['', [Validators.required]],
      isOpen: ['', [Validators.required]],
      credit: [{ value: '', disabled: true }, [Validators.required]],
      courseType: [{ value: '', disabled: true }, [Validators.required]],
      teacherName: [{ value: '', disabled: true }],
      degreeType: [{ value: '', disabled: true }],
      evaluationMode: ['', [Validators.required]],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<CourseTeacherDTO>>();

  /**
   * form组件
   */
  @ViewChild('myForm', { static: false })
  public myForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 课程类型信息
   */
  courseType: CourseTypeDTO = {
    id: null,
    code: null,
    name: null,
    courseBaseType: null,
    showOrder: 0,
  };

  /**
   * 课程信息
   */
  course: CourseDTO = {
    id: null,
    code: '',
    name: null,
    courseType: this.courseType,
    evaluationMode: null,
    credit: null,
    showOrder: 0,
  };

  /**
   * 教师信息
   */
  teacher: TeacherDTO = {
    id: null,
    code: '',
    name: '',
    gender: '',
    degreeType: '',
    birthDate: '',
    joinTime: '',
    isSenator: false,
    isInstructor: false,
  };

  /**
   * 课程开课信息
   */
  courseTeacher: CourseTeacherDTO = {
    id: null,
    year: '',
    termType: '',
    evaluationMode: '',
    isOpen: true,
    course: this.course,
    teacher: this.teacher,
    nextYear: null,
  };

  /**
   * 课程下拉
   */
  courseList: Array<CourseDTO>;
  /**
   * 教师下拉
   */
  teacherList: Array<TeacherDTO>;

  /**
   * 课程下拉选择列表
   */
  courseColumns: STColumn[] = [
    {
      title: '序号',
      type: 'no',
      width: '2%',
      className: 'text-center',
    },
    {
      title: '课程编号',
      index: 'code',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '课程名称',
      index: 'name',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '课程类型',
      render: 'courseType',
      width: '4%',
      className: 'text-center',
      default: '无',
      format(item) {
        return item.courseType.courseBaseType
          ? item.courseType.name +
              '/' +
              [
                item.courseType.courseBaseType === 'REQUIRED_COURSE'
                  ? '必修课'
                  : item.courseType.courseBaseType === 'OPTIONAL_COURSE'
                  ? '任选课'
                  : item.courseType.courseBaseType === 'RESTRICTED_COURSE'
                  ? '限选课'
                  : '',
              ]
          : item.courseType.name;
      },
    },
    {
      title: '可修读学分',
      index: 'credit',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '考核方式',
      index: 'evaluationMode',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '显示顺序',
      index: 'showOrder',
      width: '3%',
      className: 'text-center',
    },
  ];

  /**
   * 教师下拉选择列表
   */
  teacherColumns: STColumn[] = [
    {
      title: '序号',
      type: 'no',
      width: '2%',
      className: 'text-center',
    },
    {
      title: '所属学院',
      index: 'academyName',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '教师编号',
      index: 'code',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '教师名称',
      index: 'name',
      width: '4%',
      className: 'text-center',
    },
    {
      title: '性别',
      index: 'gender',
      width: '4%',
      className: 'text-center',
      format(item) {
        return item.gender === 'MALE' ? '男' : '女';
      },
    },
    {
      title: '学历',
      index: 'degreeType',
      width: '4%',
      className: 'text-center',
      format(item) {
        return item.degreeType === 'MIDDLE_SCHOOL'
          ? '初中'
          : item.degreeType === 'SECONDARY'
          ? '中专'
          : item.degreeType === 'HIGH_SCHOOL'
          ? '高中'
          : item.degreeType === 'ASSOCIATE'
          ? '大专'
          : item.degreeType === 'BACHELOR'
          ? '本科'
          : item.degreeType === 'GRADUATE'
          ? '研究生'
          : item.degreeType === 'DOCTORAL'
          ? '博士'
          : item.degreeType === 'POST_DOCTORAL'
          ? '博士后'
          : '无';
      },
    },
    {
      title: '是否教务员',
      index: 'isSenator',
      width: '4%',
      className: 'text-center',
      format(item) {
        return item.isSenator ? '是' : '否';
      },
    },
    {
      title: '是否辅导员',
      index: 'isInstructor',
      width: '4%',
      className: 'text-center',
      format(item) {
        return item.isInstructor ? '是' : '否';
      },
    },
    {
      title: '入职时间',
      index: 'joinTime',
      width: '3%',
      className: 'text-center',
      format(item) {
        return format(item.joinTime, 'YYYY-MM-DD');
      },
    },
  ];

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.myForm.form);
  }

  /**
   * 获取选中的课程
   * @param $event 选中的课程
   */
  getCourseChange($event) {
    this.courseTeacher.course = $event;
  }
  /**
   * 获取选中的教师
   * @param $event 选中的教师
   */
  getTeacherChange($event) {
    this.courseTeacher.teacher = $event;
  }

  /**
   * 修改或新增课程开课信息
   * @param isPreView 是否预览
   * @param item 课程开课信息
   */
  edit(isPreView: boolean, item: CourseTeacherDTO) {
    this.isPreView = isPreView;

    this.courseTeacher = this.initCourseTeacher(item);
    this.isVisible = true;

    // 获取所有课程
    this.courseService.findAllBySort('showOrder', 'asc').subscribe(data => {
      this.courseList = data;
    });
    // 获取所有教师
    this.teacherService.findAllBySort('id', 'asc').subscribe(data => {
      this.teacherList = data;
    });
  }

  /**
   * 初始化课程开课信息
   */
  initCourseTeacher(item: CourseTeacherDTO): CourseTeacherDTO {
    return {
      id: item ? item.id : null,
      year: item ? item.year : null,
      evaluationMode: item ? item.evaluationMode : null,
      termType: item ? item.termType : null,
      isOpen: item ? item.isOpen : true,
      course: item ? item.course : this.course,
      teacher: item ? item.teacher : this.teacher,
      nextYear: item ? Number.parseInt(item.year, 10) + 1 : null,
    };
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (this.courseTeacher.year === null) {
      this.msg.error('学年必选');
      return false;
    } else {
      this.courseTeacher.year = format(this.courseTeacher.year, 'YYYY');
    }
    if (this.courseTeacher.termType === null) {
      this.msg.error('学期必选');
      return false;
    }
    if (this.courseTeacher.evaluationMode === null) {
      this.msg.error('考核方式必选');
      return false;
    }
    if (!this.courseTeacher.course) {
      this.msg.error('课程必选');
      return false;
    }
    if (!this.courseTeacher.teacher) {
      this.msg.error('教师必选');
      return false;
    }

    return true;
  }

  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.courseTeacher.id) {
      // id为空，为新建
      this.courseTeacherService.create(this.courseTeacher).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('保存失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，为修改
      this.courseTeacherService.complete(this.courseTeacher.id, this.courseTeacher).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: CourseTeacherDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }
  ngOnInit() {}
}
